<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use \think\Db;
use app\admin\model\News as NewsModel;//管理员模型
use app\admin\controller\Permissions;
class News extends Permissions
{
    /**
     * 新闻列表
     * @return [type] [description]
     */
    public function index()
    {
        // //新闻类别
        // $type = Db::name("news_type")->select();
        // $this->assign('type',$type);

        $title=trim($this->request->Post('title'));
        $type=$this->request->Post('type');
        if($title !='') $where['title']= ['like','%' . $title . '%'];
        if($type !='') $where['type']= ['=',$type];
        //关联查询

        // $join=[
        //     ["news_type t","n.type_id=t.id","LEFT"],
        // ];
        // if(empty($where)){
        //     $news=Db::name('news')->alias("n")->join($join)->field(["n.*","t.type"])->order(["n.sort"=>"desc","n.id"=>"desc"])->paginate(10);
        // }
        // elseif(!empty($where['n.title']) and empty($where['n.type_id'])){
        //     $news=Db::name('news')->where($where)->alias("n")->join($join)->field(["n.*","t.type"])->order(["n.sort"=>"desc","n.id"=>"desc"])->paginate(10,true,['query'=>request()->Post()]);
        // }elseif(!empty($where['n.type_id'])){
        //     $news=Db::name('news')->where($where)->alias("n")->join($join)->field(["n.*","t.type"])->order(["n.type_sort"=>"asc","n.id"=>"desc"])->paginate(10,true,['query'=>request()->Post()]);
        // }
        $news = empty($where)?Db::name('news')->order(["type_sort"=>"asc","id"=>"desc"])->paginate(10,false,['query'=>request()->Post()]): Db::name('news')->where($where)->order("id","desc")->paginate(10,false,['query'=>request()->Post()]);
        $this->assign('news',$news);
        // var_dump($news);
        return $this->fetch();
    }

    /**
     * 添加新闻
     */
    public function add(){
        //实例化模型
        // $model=new NewsModel();
        // $type=Db::name("news_type")->select();
        // // var_dump($type);
        // $this->assign('type',$type);
        //判断是不是操作数据库  
        if($this->request->isPost()){

            $post=$this->request->Post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            
            // $validate = new \think\Validate([
                // ['type', 'require', '新闻类型必选!'],
                // ['type_sort', 'number', '排序格式不正确,请填数字'],
 
            // ]);
            //验证部分数据合法性
            // if (!$validate->check($post)) {
                // $this->error('提交失败：' . $validate->getError());
            // }
            $id=$this->request->Post("id");
            
            if($id!=''){
                $old_img=Db::name("news")->where('id',$id)->value('img');
            }
              // 获取表单上传文件 例如上传了001.jpg
            $file = Request()->file("img");
            if(!empty($file)){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/news');
                if($info){
                    $img =$info->getSaveName();
                    @unlink($_SERVER['DOCUMENT_ROOT']."shanghai/public/uploads/news/".$old_img);
                }else{
                    echo $file->getError();
                }
            }else{
                $img=$old_img;
            }
            if($post['type_sort']==''){
                $type_sort=999;
            }else{
                $type_sort=$post['type_sort'];
            }
            $data=[
                    'title'=>$post['title'],
                    'subtitle'=>$post['subtitle'],
                    'content'=>$post['content'],
					'tit'=>$post['tit'],
                    'key'=>$post['key'],
                    'dec'=>$post['dec'],
                    'author'=>$post['author'],
					'type'=>$post['type'],
                    'type_sort'=>$type_sort,
                    'img'=>$img,
                    "create_time"=>time()
                ];
            if($id==null){       
                $id=Db::name('news')->insert($data);
                if($id==false) return $this->error('保存失败');   
            }else{
                $data1=[
                    'title'=>$post['title'],
                    'subtitle'=>$post['subtitle'],
                    'content'=>$post['content'],
					'tit'=>$post['tit'],
                    'key'=>$post['key'],
                    'dec'=>$post['dec'],
                    'author'=>$post['author'],
					'type'=>$post['type'],
                    'img'=>$img,
                    'type_sort'=>$type_sort,
                ];
                $res = Db::name('news')->where('id',$id)->update($data1);
                if($res==false) return $this->error('修改失败');     
            }
            return $this->success("新闻保存成功",'admin/news/index');
        }elseif($this->request->has('id')){
            //实例化模型
            $model=new NewsModel();
            //获取对应数据id
            $id=$this->request->param("id");
            $news=$model->where("id",$id)->find();
            // var_dump($friendly);
            $this->assign("news",$news->getdata());
            return $this->fetch("news/add");
        }else{
            return $this->fetch();
        }
    }


     /**
     * 新闻删除
     * @return [type] [description]
     */
    public function delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if(false == Db::name('news')->where('id',$id)->delete()) {
                return 1;
            } else {
                return 0;
            }
        }
    }


    /**
     * 新闻类别
     * 
     */
    public  function news_type(){
        $type=Db::name("news_type")->order("id","desc")->paginate(10);
        $this->assign("type",$type);
        return $this->fetch("news/news_type");
    }

        /**
     * 添加新闻类别
     */
    public function type_add(){
        //实例化模型
        $model=new NewsModel();

        //判断是不是操作数据库  
        if($this->request->isPost()){

            $post=$this->request->Post();
            $id=$this->request->Post("id");
            if($id==''){       
                $id=Db::name('news_type')->insert($post);
                if($id==false) return $this->error('修改失败');   
            }else{
                $res =Db::name('news_type')->where('id',$id)->update($post,$id);
                if($res==false) return $this->error('修改失败');     
            }
            return $this->success('新闻保存成功','admin/news/news_type');
        }else{
            return $this->fetch();
        }
    }

    /**
     * 修改页面
     */
    public function type_edit(){
        //实例化模型
        // $model=new NewsModel();
        //获取对应数据id
        $id=$this->request->param("id");
        $type=Db::name("news_type")->where("id",$id)->find();
        // var_dump($friendly);
        $this->assign("type",$type);
        return $this->fetch("news/type_add");
    } 


         /**
     * 新闻类别删除
     * @return [type] [description]
     */
    public function type_delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if(false == Db::name('news_type')->where('id',$id)->delete()) {
                return 1;
            } else {
                // addlog($id);//写入日志
                return 0;
            }
        }
    }

    
}
